package com.jackchong.base;

import android.os.Handler;
import android.os.Looper;
import android.view.MotionEvent;
import android.view.View;

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2019-07-18
 * desc   :
 */
public abstract class LongTouchEvent implements View.OnTouchListener {


    public abstract void onDown();

    public abstract void onUp();

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private static final int MAX_OFFSET = 100;

    private float mDownX, mDownY;
    private Runnable mRunnable;
    private boolean isPress;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDownX = event.getX();
                mDownY = event.getY();
                mRunnable = () -> {
                    isPress = true;
                    onDown();
                    mHandler.postDelayed(mRunnable, 50);
                };
                mHandler.postDelayed(mRunnable, 2000);
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = event.getX() - mDownX;
                float dy = event.getY() - mDownY;

                if (Math.abs(dx) > MAX_OFFSET || Math.abs(dy) > MAX_OFFSET){
                    mHandler.removeCallbacks(mRunnable);
                }
                mDownX = event.getX();
                mDownY = event.getY();

                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (isPress){
                    onUp();
                    isPress = false;
                }
                mHandler.removeCallbacks(mRunnable);
                break;
        }
        return false;
    }
}
